package cn.maxhou.controller;

import cn.maxhou.entity.SysUser;
import cn.maxhou.ex.LoginException;
import cn.maxhou.service.SysUserService;
import cn.maxhou.util.Constants;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.view.UrlBasedViewResolver;


@Controller
public class LoginController extends BaseController {
    @Autowired
    private SysUserService sysUserService;


    @Autowired
    private HttpServletRequest request;

    /**获取request对象*/
    public HttpServletRequest request(){
        return request;
    }

    @GetMapping("/login")
    public String toLogin(){
        //由于1ogin.jsp页面不在WEB-INF下，所以不能返回逻辑视图名称
        //需要使用forward：前缀告知SpringMvc转发到根路径下的login.jsp
        return forward("/login.jsp");
    }

    @Transactional
    @PostMapping("/login")
        public String login(@RequestParam("account") String account, @RequestParam String password, HttpServletRequest request,HttpSession session){
        SysUser loginUser =sysUserService.login(account,password);
        if(loginUser != null){
            //登录成功,用户信息存入session
            session().setAttribute(Constants.SESSION_USER,loginUser);
            //重定向到后台首页
            return redirect("/main/index");
        }else {
            //设置错误信息到request作用域
            //request().setAttribute(Constants.REQUEST_ERROR,"用户名或密码错误!");
            //转发到登录页面
            //return forward("/login.jsp");
            throw  new LoginException("登录失败,用户名或密码错误!");
        }
    }

    //跳转到后台首页
    @GetMapping("/main/index")
    public String index(){
        return "index";
    }

    @GetMapping("/ex")
    public void throwException(){
        throw new RuntimeException("测试不同异常类映射到不同页面!");
    }

    //注销
    @GetMapping("/logout")
    public String logout(){
        session().removeAttribute(Constants.SESSION_USER);
        return forward("/login.jsp");
    }

    /*@ExceptionHandler(value = RuntimeException.class)
    public String handlerException(RuntimeException e,HttpServletRequest request) {
        //设置捕获的错误对象到request作用域
        request.setAttribute(Constants.REQUEST_ERROR,e);
        //跳转到异常页面:/WEB-INF/jsp/500.jsp
        return "500";
    }*/
}
